## Make table of Correlations: Meaning x Flexibility x Pathways

# Create Pairwise Correlation Table
data <- clean_LISS_data

# Assuming your data frame is named 'data' and includes the relevant variables
vars <- data[, c("high_contact", "high_computer", "high_meaning", "high_flex", "high_telecommute")]
custom_names <- c("High Contact", "High Computer", "High Meaning", "Schedule Adaptability", "Telecommuting")

# Perform pairwise complete observations
corr_matrix <- rcorr(as.matrix(vars), type = "pearson")

# Extract the correlation coefficients and p-values
correlations <- corr_matrix$r
p_values <- corr_matrix$P

# Apply the Bonferroni correction to the p-values
adjusted_p_values <- matrix(p.adjust(p_values, method = "bonferroni"), nrow = nrow(p_values), ncol = ncol(p_values))

# Get table ready for export to latex (bold font if p-value < 0.05)
format_correlations <- function(cor, p_adj) {
  formatted_cor <- matrix("", nrow = nrow(cor), ncol = ncol(cor))
  for (i in 1:nrow(cor)) {
    for (j in 1:ncol(cor)) {
      if (i == j) {
        formatted_cor[i, j] <- sprintf("%.2f", cor[i, j])
      } else if (p_adj[i, j] < 0.05) {
        formatted_cor[i, j] <- sprintf("\\textbf{%.2f}", cor[i, j])
      } else {
        formatted_cor[i, j] <- sprintf("%.2f", cor[i, j])
      }
    }
  }
  return(formatted_cor)
}

# Format the correlation matrix
formatted_correlations <- format_correlations(correlations, adjusted_p_values)

# Convert the matrix to a data frame for xtable
formatted_correlations_LISS <- as.data.frame(formatted_correlations)
rownames(formatted_correlations_LISS) <- custom_names
colnames(formatted_correlations_LISS) <- custom_names

# Export Correlations Table
latex_table_corr_LISS <- xtable(formatted_correlations_LISS)
latex_code <- print.xtable(latex_table_corr_LISS, include.rownames = TRUE, include.colnames = TRUE, floating = FALSE, type = "latex", sanitize.text.function = function(x){x})
writeLines(latex_code, file.path(graph_dir, "table_corr_LISS.txt"))